package com.example.reggie.Controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.reggie.common.R;
import com.example.reggie.dto.DishDto;
import com.example.reggie.entity.Category;
import com.example.reggie.entity.Dish;
import com.example.reggie.entity.DishFlavor;
import com.example.reggie.service.CategoryService;
import com.example.reggie.service.DishFlavorService;
import com.example.reggie.service.DishService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.lang.management.PlatformManagedObject;
import java.util.Calendar;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


/**
 * Redis 缓存思路：
 *      1. 在list方法中，从redis中获取菜品，有则直接返回，没有则查询数据库，并将数据缓存到redis中
 *      2. 在update 和save方法中，添加清理缓存逻辑
 */
@Slf4j
@RestController
@RequestMapping("/dish")
@Api(tags = "菜品相关接口")
public class DishController {

    @Autowired
    DishService dishService;

    @Autowired
    DishFlavorService dishFlavorService;

    @Autowired
    CategoryService categoryService;

    @Autowired
    RedisTemplate redisTemplate;

    /**
     * 新增菜品
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto){

       // log.info(dishDto.toString());
        dishService.saveWithFlavor(dishDto);
        return R.success("新增菜品成功");
    }

    /**
     * Dish分页
     * 思路：返回泛型为<DishDto>的Page对象  ，展示dish的全部属性和Category的name属性
     *      实现泛型为<Dish>Page对象的封装 ，然后拷贝除records属性外的其他属性 到 Dto的 page对对象中
     *      遍历Dish 的recorods 属性，通过catagory_id 获取catagory表中的 name属性 ，再封装到Dto的records中
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize,String name){

        //构造page对象
        Page<Dish> page1 = new Page<>(page,pageSize);

        //新建泛型为dishDto 的 Page对象
        Page<DishDto> dishDtoPage = new Page<>();

        //构造条件构造器
        LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper();

        //根据name是否为空值， 模糊查询
        lambdaQueryWrapper.like(name!= null,Dish::getName,name); 

        //排序
        lambdaQueryWrapper.orderByDesc(Dish::getPrice);

        dishService.page(page1,lambdaQueryWrapper);


        //对象拷贝
        BeanUtils.copyProperties(page1,dishDtoPage,"records");

        List<Dish> records = page1.getRecords();

        List<DishDto> list = records.stream().map((item)->{
            //新建DishDto 对象
            DishDto dishDto = new DishDto();

            //将Dish 中的属性拷贝到Dto对象中
            BeanUtils.copyProperties(item,dishDto);

            //通过Dish对象中来获取分类id
            Long categoryId = item.getCategoryId();

            //根据分类id 查询分类对象
            Category category = categoryService.getById(categoryId);
            //为Dto赋 分类name
            dishDto.setCategoryName(category.getName());
            return dishDto;
            }).collect(Collectors.toList());


        dishDtoPage.setRecords(list);

        return R.success(dishDtoPage);
    }

    /**
     * 获取菜品
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> list(@PathVariable long id){
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    /**
     * 更新菜品
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<String> updateWithFlavor(@RequestBody DishDto dishDto){
        dishService.updateWithFlavor(dishDto);
//        //清除所有菜品缓存数据
//        Set keys = redisTemplate.keys("dish_*");
//        redisTemplate.delete(keys);

        //清除具体某一个菜品类下的缓存数据
        String keys = "dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(keys);
        return R.success("菜品更新成功");
    }

    /**
     * 客户端菜品展示
     * 思路：
     *  返回泛型为DishDto 的List对象  DishDto中包括Dish 属性 和 DishFlavor集合
     *  查询Dish, 返回list ，stream流操作 ，copy item -> DishDto  ，
     *  查询DishFlavor ，返回list， 赋值给DishDto ，返回DishDto的list
     *
     *  Redis 缓存思路
     *      从redis中获取，获取不到，到数据库中查询并缓存到redis中
     *              动态构造key,
     *              key: dish_categoryId_status
     *              value: List<DIshDto>
     * @param dishDto
     * @return
     */
    @GetMapping("/list")
    public R<List<DishDto>> list(DishDto dishDto){

        log.info("");
        //缓存逻辑
        List<DishDto> list1 = null;
        String key = "dish_" + dishDto.getCategoryId() + "_" + dishDto.getStatus();
        list1  = (List<DishDto>) redisTemplate.opsForValue().get(key);
        if(list1 != null)
            return R.success(list1);


        //条件构造器
        LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Dish::getCategoryId,dishDto.getCategoryId());
        lambdaQueryWrapper.eq(Dish::getStatus,1);
        lambdaQueryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List<Dish> list = dishService.list(lambdaQueryWrapper);
        list1 = list.stream().map((item->{
            DishDto dto = new DishDto();
            BeanUtils.copyProperties(item,dto);
            Long dishId = item.getId();
            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
            lambdaQueryWrapper1.eq(DishFlavor::getDishId,dishId);
            List<DishFlavor> dishFlavorList = dishFlavorService.list(lambdaQueryWrapper1);
            dto.setFlavors(dishFlavorList);
            return dto;
        })).collect(Collectors.toList());

        redisTemplate.opsForValue().set(key,list1,60L, TimeUnit.MINUTES);

        return R.success(list1);
    }

    /**
     * 删除菜品
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> delete(@RequestParam List<Long> ids){
        dishService.removeByIds(ids);
        return R.success("删除成功");
    }

    /**
     * 修改状态 1 启售 0 停售
     * @param ids
     * @param
     * @return
     */
    @PostMapping("/status/{b}")
    public R<String> status(@PathVariable Integer b ,@RequestParam List<Long> ids){
        log.info("");
        Long  category = null;
        for (Long id: ids) {
            Dish byId = dishService.getById(id);
            byId.setStatus(b);
            dishService.updateById(byId);

            category = byId.getCategoryId();
        }

        String keys = "dish_" + category + "_1";
        redisTemplate.delete(keys);
        return R.success("");
    }


    /**
     * 菜品展示
     * @param dish
     * @return
     */
    //@GetMapping("/list")
    public R<List<Dish>> list1(Dish dish){
        log.info("");
        //条件构造器
        LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Dish::getCategoryId,dish.getCategoryId());
        lambdaQueryWrapper.eq(Dish::getStatus,1);
        lambdaQueryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List<Dish> list = dishService.list(lambdaQueryWrapper);

        return R.success(list);
    }
}
